#include "serialportutil.h"

SerialPortUtil::SerialPortUtil(QObject *parent) : QObject(parent)
{
    m_serial = new QSerialPort();

    // 同步读取时不能使用，否则被槽函数接收后，同步函数一直读取不到结果
    //connect(m_serial, SIGNAL(readyRead()), this, SLOT(readyRead_slot()));
}

SerialPortUtil::~SerialPortUtil()
{
    delete m_serial;
}

QStringList SerialPortUtil::getAvailablePortNameList()
{
    QStringList portName;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        portName << info.portName();
    }
    return portName;
}

bool SerialPortUtil::openPort(QString portName, qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::Parity parity, QSerialPort::StopBits stopBits)
{
    m_serial->setPortName(portName);
    m_serial->setBaudRate(baudRate);
    m_serial->setDataBits(dataBits);
    m_serial->setParity(parity);
    m_serial->setStopBits(stopBits);

    if (m_serial->open(QIODevice::ReadWrite)) {
        return true;
    } else {
        return false;
    }
}

bool SerialPortUtil::isOpen()
{
    return m_serial->isOpen();
}

void SerialPortUtil::closePort()
{
    qDebug() << "close port";
    qDebug() << m_serial->isOpen();
    if (m_serial->isOpen()) {
        m_serial->close();
        m_serial->clear();
    }
}

void SerialPortUtil::write(QByteArray data)
{
    m_serial->write(data);
}

void SerialPortUtil::write(const char *data, qint64 len)
{
    m_serial->write(data, len);
}

QString SerialPortUtil::bytes2Hex(QByteArray data)
{
    QString ret(data.toHex().toUpper());
    int len = ret.length()/2;
    for (int i = 1; i < len; i++) {
        ret.insert(2*i+i-1, " ");
    }
    return ret;
}

QByteArray SerialPortUtil::hex2Bytes(QString data)
{
    bool ok;
    QByteArray ret;
    data = data.trimmed();
    data = data.simplified();
    QStringList sl = data.split(" ");
    foreach (QString s, sl) {
        if (!s.isEmpty()) {
            char c = s.toInt(&ok, 16)&0xFF;
            if (ok) {
                ret.append(c);
            } else {
                qDebug() << "非法的16进制字符" << s;
            }
        }
    }
    return ret;
}


void SerialPortUtil::readyRead_slot()
{
    QByteArray data = m_serial->readAll();
    qDebug() << "************";
    qDebug() << data;
    emit readed(data);
}

QByteArray SerialPortUtil::sendAndRead(QString data)
{
    QByteArray sendBytes = QByteArray::fromHex(data.toLatin1());
    m_serial->write(sendBytes);
    if (!m_serial->waitForBytesWritten(5000)) {
        qDebug() << "写入超时";
        return "";
    }

    QByteArray recvBytes;
    while(m_serial->waitForReadyRead(5000)) {
        // 读取串口数据
        recvBytes = m_serial->readAll();
        if (!recvBytes.isEmpty()) {
            break;
        }
    }
    qDebug() << recvBytes;
    qDebug() << "1111111";
    qDebug() << bytes2Hex(recvBytes.mid(3, 1));
    qDebug() << "222222";
    qDebug() << "recvicved";
    return recvBytes;
    //return bytes2Hex(recvBytes);
}
